package com.base.custom

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet

class RoundImage(context: Context, attrs: AttributeSet?, defStyleAttr: Int): androidx.appcompat.widget.AppCompatImageView(context, attrs,defStyleAttr) {
    constructor(context: Context): this(context,null)
    constructor(context: Context,attrs: AttributeSet?): this(context,attrs,0)

    private val clipPath = Path()
    private val rect = RectF()
    private var init =  false
    var topL = 0f
        set(value) {
            field = value
            if(init){
                init(width,height)
                postInvalidate()
            }
        }
    var topR = 0f
        set(value) {
            field = value
            if(init){
                init(width,height)
                postInvalidate()
            }
        }
    var bottomL = 0f
        set(value) {
            field = value
            if(init){
                init(width,height)
                postInvalidate()
            }
        }
    var bottomR = 0f
        set(value) {
            field = value
            if(init){
                init(width,height)
                postInvalidate()
            }
        }

    private val radiusArray = floatArrayOf(topL,topL,topR,topR,bottomR,bottomR,bottomL,bottomL)
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        init = true
        rect.set(0f,0f,w.toFloat(),h.toFloat())
        init(w,h)
    }

    private fun init(w: Int, h: Int){
        clipPath.reset()
        val x = w/2f
        val y = h/2f
        radiusArray[0] = topL.coerceAtMost(x)
        radiusArray[1] = topL.coerceAtMost(y)
        radiusArray[2] = topR.coerceAtMost(x)
        radiusArray[3] = topR.coerceAtMost(y)
        radiusArray[4] = bottomR.coerceAtMost(x)
        radiusArray[5] = bottomR.coerceAtMost(y)
        radiusArray[6] = bottomL.coerceAtMost(x)
        radiusArray[7] = bottomL.coerceAtMost(y)
        clipPath.addRoundRect(rect,radiusArray,Path.Direction.CW)
    }

    fun setRadius(topL: Float,topR: Float,bottomL: Float,bottomR: Float){
        this.topL = topL
        this.topR = topR
        this.bottomL = bottomL
        this.bottomR = bottomR
    }



    override fun draw(canvas: Canvas?) {
        canvas?:return
        canvas.clipPath(clipPath)
        super.draw(canvas)
    }
}